package com.xiaoq.coms;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

@SuppressWarnings("serial")
public class RepoException extends RuntimeException {
	public RepoException() {
		super();
	}

	public RepoException(String msg, Throwable cause) {
		super(msg, cause);
	}

	public RepoException(String msg) {
		super(msg);
	}

	public RepoException(Throwable cause) {
		super(cause);
	}
	
	public static RepoException wrapSQLException(SQLException e, PreparedStatement sta, String sql, @SuppressWarnings("rawtypes") List params) {
		if(sta != null) {
			StringBuilder sbd = new StringBuilder("数据库操作失败。\n");
			sbd.append(e.getMessage()).append("。\n");
			int posQuestion = sql.indexOf("?");
			String sqlWithValues = sql;
			if(params != null && posQuestion > 0) {
				try {
					String val = null;
					for(Object obj : params) {
						if(obj instanceof String) {
							val = obj == null ? "null" : "'" + obj + "'";
						} else if(obj instanceof Number) {
							val = obj == null ? "null" : obj + "";
						} else {
							val = obj == null ? "null" : obj.toString();
						}
						sqlWithValues = sqlWithValues.replaceFirst("\\?", val);
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				sbd.append("SQL语句 ，").append(sqlWithValues).append("。\n");
			} else {
				if(StringUtils.isNotBlank(sql)) {
					sbd.append("SQL语句 ，").append(sql).append("。\n");
				}
			}
			return new RepoException(sbd.toString(), e);
		} else {
			return new RepoException("创建SQL失败，SQL = " + sql, e);
		}
	}
}
